package com.cyan.note.service.impl;

import com.cyan.note.dto.auth.LoginRequest;
import com.cyan.note.dto.auth.LoginResponse;
import com.cyan.note.entity.Shop;
import com.cyan.note.entity.User;
import com.cyan.note.enums.UserRole;
import com.cyan.note.mapper.ShopMapper;
import com.cyan.note.mapper.UserMapper;
import com.cyan.note.service.UserService;
import com.cyan.note.util.JwtUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * 用户服务实现类
 * 
 * @author ZhangzhenYu
 * @since 2025-01-13
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {
    
    private final UserMapper userMapper;
    private final ShopMapper shopMapper;
    private final PasswordEncoder passwordEncoder;
    private final JwtUtil jwtUtil;
    
    @Override
    public LoginResponse login(LoginRequest loginRequest) {
        // 1. 根据用户名查找用户
        User user = findByUsername(loginRequest.getUsername());
        if (user == null) {
            throw new RuntimeException("用户名或密码错误");
        }
        
        // 2. 验证密码
        if (!checkPassword(loginRequest.getPassword(), user.getPassword())) {
            throw new RuntimeException("用户名或密码错误");
        }
        
        // 3. 检查用户状态
        if (!"active".equals(user.getStatus())) {
            throw new RuntimeException("账户已被禁用，请联系管理员");
        }
        
        // 4. 获取店铺信息（如果用户是店长或打手）
        Shop shop = null;
        if (user.getShopId() != null) {
            shop = shopMapper.selectById(user.getShopId());
        }
        
        // 5. 生成JWT Token
        String token = jwtUtil.generateToken(
            user.getId(),
            user.getUsername(), 
            user.getRole(),
            user.getShopId()
        );
        
        // 6. 构建用户信息
        LoginResponse.UserInfo userInfo = LoginResponse.UserInfo.builder()
                .userId(user.getId())
                .username(user.getUsername())
                .realName(user.getRealName())
                .role(user.getRole())
                .roleName(getRoleName(user.getRole()))
                .shopId(user.getShopId())
                .shopName(shop != null ? shop.getName() : null)
                .phone(user.getPhone())
                .status(user.getStatus())
                .build();
        
        // 7. 构建登录响应
        LoginResponse response = LoginResponse.builder()
                .token(token)
                .tokenType("Bearer")
                .userInfo(userInfo)
                .build();
        
        log.info("用户 {} 登录成功，角色: {}", user.getUsername(), user.getRole());
        return response;
    }
    
    @Override
    public User findByUsername(String username) {
        return userMapper.findByUsername(username);
    }
    
    @Override
    public User findById(Long userId) {
        return userMapper.selectById(userId);
    }
    
    @Override
    public boolean checkPassword(String rawPassword, String encodedPassword) {
        return passwordEncoder.matches(rawPassword, encodedPassword);
    }
    
    @Override
    public String getRoleName(String roleCode) {
        try {
            UserRole userRole = UserRole.fromCode(roleCode);
            return userRole.getName();
        } catch (Exception e) {
            return "未知角色";
        }
    }
}